from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404

from forfood.restaurant.models import Restaurant
from forfood.helpers.user_helper import *
from forfood.restaurant.forms import *
from forfood.menu.models import *
from forfood.comment.models import *
from forfood.customer.models import *
import datetime
import re

def common_variables(restaurant):
    menus = restaurant.menu_set.all()
    #for i in menus:
    #    if i.in_use:
    #        menu = i
    forms = {'form_ac':AddMenuCategoryForm(),
    	     'form_ec':EditMenuCategoryForm(),
    	     'form_ai':AddMenuItemForm(),
    	     'form_ei':EditMenuItemForm(),}
    	     
    if not menus:
        menu = Menu.objects.create(menu_name="%s's menu"%(restaurant.username), restaurant=restaurant)
    else:    
        menu = menus[0]  
              
    categories = menu.menucategory_set.all() 
      	     
    value = []   
    for i in categories:
        value.append([i.name,i.name])
        
    forms['form_ec'].set_choices(value)
    forms['form_ai'].set_choices(value)
    forms['form_ei'].set_choices(value)
    
    orders = restaurant.order_set.filter(status__gt = 0)
    
    return {'restaurant':restaurant,
    	    'menu':menu,
    	    'categories':categories,
    	    'form_ac':forms['form_ac'],
    	    'form_ec':forms['form_ec'],
    	    'form_ai':forms['form_ai'],
    	    'form_ei':forms['form_ei'],
            'orders':orders
    	    }

def handle_post(request, variables):
    menu = variables['menu']
    categories = variables['categories']
    category_choices = []
    for i in categories:
        category_choices.append([i.name,i.name]) 
    
    if request.POST.get('form_ac', ''):
        form = AddMenuCategoryForm(request.POST)        
        if form.is_valid():
            ###
            mc = MenuCategory(menu=menu, name=form.cleaned_data['name'])
            menu.menucategory_set.add(mc)
            return "add c successfully"
        return form.errors
            
    if request.POST.get('form_ec', ''):
        form = EditMenuCategoryForm(request.POST)
        form.set_choices(category_choices)
        
        if form.is_valid():
            try:
                print form.cleaned_data['old_category']
                print form.cleaned_data['new_category']
                mc = MenuCategory.objects.get(name = form.cleaned_data['old_category'])
                mc.name = form.cleaned_data['new_category']
                print mc.name
                mc.save()
            except:
                return "object not find"
            return "edit c successfully"
        return form.errors
    
    if request.POST.get('form_ai', ''):
        form = AddMenuItemForm(request.POST)
        form.set_choices(category_choices)
        if form.is_valid():
            name = form.cleaned_data['name']
            category = MenuCategory.objects.get(name = form.cleaned_data['category'])
            price = form.cleaned_data['price']
            description = form.cleaned_data['description']
            mi = MenuItem.objects.create(name = name, 
            				 category = category,
            				 price = price,
            				 description = description)
            mi.save()
            return "add i successfully"
        return form.errors
    
    if request.POST.get('form_ei', ''):
        form = EditMenuItemForm(request.POST)
        form.set_choices(category_choices)
        if form.is_valid():
            ###
            return "edit i successfully"
        return form.errors
        
    return "nothing posted"

def restaurant_base_process(request):
    restaurant = find_restaurant(request.user)
    if not (restaurant):
        raise Http404
        
    variables = common_variables(restaurant)
    
    if request.method == 'POST':
        errors = handle_post(request, variables)
        print errors
        variables = common_variables(restaurant)
        variables['errors'] = errors
        print variables['errors']
    return variables
        
def restaurant_manage_page(request):
    variables = restaurant_base_process(request)
        
    return render_to_response('restaurant_manage/main.html', RequestContext(request,variables))

def restaurant_manage_menu_page(request):
    variables = restaurant_base_process(request)
        
    return render_to_response('restaurant_manage/menu.html', RequestContext(request,variables))
    
def restaurant_manage_order_page(request):
    variables = restaurant_base_process(request)
        
    return render_to_response('restaurant_manage/order.html', RequestContext(request,variables))    

from time import time
def restaurant_update(request):
    restaurant = find_restaurant(request.user)
    if restaurant:
        current = int(time())
        restaurant.last_update = current
        restaurant.save()
    else:
        print "restaurant not find"
    
    raise Http404
#-------------------------------------------------------------------------------------------------------------    
def restaurant_page(request, uid):
    customer = find_customer(request.user)
    restaurant = find_restaurant(request.user)
    try:
        restaurant_v = Restaurant.objects.get(id=uid)
    except:
        raise Http404
    restaurant_v.is_loved_by(customer)
    menus = restaurant_v.menu_set.all()          
    if not menus:
        menu = Menu.objects.create(menu_name="%s's menu"%(restaurant_v.username), restaurant=restaurant_v)
    else:    
        menu = menus[0]  
    
    customers=Customer.objects.all()
    
    if 'user-comment-content' in request.GET and request.GET['user-comment-content'] \
        and 'user-id' in request.GET and request.GET['user-id']:
        comment_content = request.GET['user-comment-content']
        customer = Customer.objects.get(id=request.GET['user-id'])
        now = datetime.datetime.now()
        Comment.objects.create(comment_content=comment_content, datestamp=now, 
                               replied_comment_id=-1, restaurant=restaurant_v,customer=customer)
    
    if 'user-comment-reply-content' in request.GET and request.GET['user-comment-reply-content'] \
        and 'user-id' in request.GET  and request.GET['user-id'] and 'replied-comment-id' in request.GET \
        and request.GET['replied-comment-id']:
        handle_reply_comment(request, restaurant_v)
    
        
    comments = restaurant_v.comment_set.all().order_by('-datestamp')
    comment_count = comments.count 
        
    
    categories = menu.menucategory_set.all() 
    return render_to_response('restaurant/main.html', RequestContext(request,locals()))

def handle_reply_comment(request, restaurant_v):
    reply_comment_content = request.GET['user-comment-reply-content']
    comment_id = request.GET['replied-comment-id']
    customer = Customer.objects.get(id=request.GET['user-id'])
    
    now = datetime.datetime.now()
    
    if(re.search(r'//#', reply_comment_content)):
        comment=Comment.objects.get(id=comment_id)
        if (comment):
            index = reply_comment_content.find('//#', 0)
            i=0
            reply_comment=''
            while i < index:
                reply_comment=reply_comment+reply_comment_content[i]
                i=i+1 
            
            
            Comment.objects.create(comment_content=reply_comment, datestamp=now, 
                               replied_comment_id=comment_id, restaurant=restaurant_v,customer=customer)
        else:
            Comment.objects.create(comment_content=reply_comment_content, datestamp=now, 
                               replied_comment_id=-1, restaurant=restaurant_v,customer=customer)
    else:
        Comment.objects.create(comment_content=comment_content, datestamp=now, 
                               replied_comment_id=-1, restaurant=restaurant_v,customer=customer)
    

#-------------------------------------------------------------------------------------------------------------  
def display_meta(request):
    values = request.META.items()
    values.sort()
    html = []
    for k, v in values:
        html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
    return HttpResponse('<table>%s</table>' % '\n'.join(html))